package com.fruit.service.packageorder.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.constants.BillConstant;
import com.fruit.constants.GoodsContant;
import com.fruit.constants.OrderConstant;
import com.fruit.constants.PayConstant;
import com.fruit.constants.RedisConstant;
import com.fruit.mapper.order.OrderMapper;
import com.fruit.mapper.packageorder.OrderPackageMapper;
import com.fruit.mapper.packageorderdetail.OrderPackageDetailMapper;
import com.fruit.mapper.pay.PayMapper;
import com.fruit.pojo.address.Address;
import com.fruit.pojo.order.Order;
import com.fruit.pojo.order.OrderConfig;
import com.fruit.pojo.orderpackage.OrderPackage;
import com.fruit.pojo.orderpackage.OrderPackageDetail;
import com.fruit.pojo.orderpackage.PackageOrderInfo;
import com.fruit.pojo.pay.TransactionFlow;
import com.fruit.pojo.user.UserReal;
import com.fruit.sdk.account.AccountManager;
import com.fruit.service.goods.GoodsManager;
import com.fruit.service.goodspackage.GoodsPackageDetailManager;
import com.fruit.service.goodspackage.GoodsPackageManager;
import com.fruit.service.order.OrderManager;
import com.fruit.service.packageorder.PackageOrderManager;
import com.fruit.service.redis.JedisUtil;
import com.fruit.service.user.UserManager;
import com.fruit.util.CommonUtil;
import com.fruit.util.CustomUtil;
import com.fruit.util.DataUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.Exceptions;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 套餐订单service
 *
 * @author Administrator
 * @version 2018.02.06 17:02
 *
 */
@Slf4j
@Service
public class PackageOrdeService implements PackageOrderManager {
	@Autowired
	private AccountManager accountService;
	@Autowired
	private GoodsPackageManager goodsPackageService;
	@Autowired
	private GoodsPackageDetailManager goodsPackageDetailService;	
	@Autowired
	private UserManager userService;	
	@Autowired
	private GoodsManager goodsService;
	@Autowired
	private JedisUtil jedisService;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private PayMapper payMapper;
	@Autowired
	private OrderPackageMapper orderPackageMapper;
	@Autowired
	private OrderPackageDetailMapper orderPackageDetailMapper;
	@Autowired
	private OrderManager orderService;
//	@Autowired
//	private MailOrderMapper mailOrderMapper;
	
	@Value("${h5_domain}")
	private String h5Domain;
	@Value("${domain}")
	private String domain;

	@Override
	public Map<String, Object> findCheckFirmOrderParams(Map<String, Object> params, String tradeId) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			// 校验参数
			if (params == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数错误!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【套餐立即购买参数校验】-----【params】" + params.toString());
			if (params.get("goodsPackageId") == null || "".equals(params.get("goodsPackageId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数商品套餐id不能为空!"));
				return resMap;
			}
			if (params.get("buyNum") == null || Integer.parseInt("" + params.get("buyNum")) <= 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数购买数量必须大于零!"));
				return resMap;
			}
			if (params.get("userId") == null || "".equals(params.get("userId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数用户id不能为空!"));
				return resMap;
			}
			// 验证用户是否实名
//			UserReal userReal = accountService.isReal(Long.parseLong("" + params.get("userId")));
//			log.info("【" +tradeId+ "】---【套餐立即购买参数校验】-----【实名认证】" + userReal.toString());
//			String userRealUrl = getUserRealUrl(userReal);
//			if (StringUtils.isNotEmpty(userRealUrl)) {
//				resMap.put("userRealUrl", userRealUrl+ "?returnUrl=" + h5Domain + "/mealDetails?id="
//						+ params.get("goodsPackageId"));
//				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_real", "用户未实名认证!"));
//				return resMap;
//			}
			// 判断商品是否存在
			Map<String, Object> pacResMap = goodsPackageService.selectRecordByKey(Long.parseLong("" + params.get("goodsPackageId")));
			log.info("【" +tradeId+ "】---【套餐立即购买参数校验】-----【判断商品是否存在】" + pacResMap.toString());
			ResultInfo ri = (ResultInfo) pacResMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				resMap.put("result", ri);
				return resMap;
			}
			@SuppressWarnings("unchecked")
			Map<String, Object> dataMap = (Map<String, Object>) pacResMap.get("data");
			if (dataMap == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "获取商品套餐异常!"));
				return resMap;
			}
			if (dataMap.get("state") == null || !GoodsContant.State.UP.getValue().equals(dataMap.get("state"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品非上架状态!"));
				return resMap;
			}
			if (GoodsContant.SaleType.YES.getValue().equals(dataMap.get("saleType"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品已售罄!"));
				return resMap;
			}
			//实际售出数量
			int realSaleNum = 0;
			if (dataMap.get("realSaleNum") != null) {
				realSaleNum=Integer.parseInt("" + dataMap.get("realSaleNum"));
			}
			//库存
			int stockNum = 0;
			if (dataMap.get("stockNum") != null) {
				stockNum=Integer.parseInt("" + dataMap.get("stockNum"));
			}
			if (stockNum <= realSaleNum ) { // 没库存则直接返回
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品已售罄!"));
				return resMap;
			}			
			// 判断金额
			BigDecimal totalPrice = DataUtil.mul(2, dataMap.get("price"), params.get("buyNum"));
			// 查看用户默认收货地址
			Address address = userService.getAddressDefaultByUserId(Integer.parseInt("" + params.get("userId")));
			// 判断用户是否登录，插入令牌
			String submitToken = CommonUtil.getUUID();
			goodsService.setToken(RedisConstant.USER_PACKAGE_SUBMIT_TOOKEN + params.get("userId"), submitToken);
			resMap.put("submitToken", submitToken);// 令牌
			resMap.put("address", address); //地址
//			resMap.put("userReal", userReal); // 实名认证
			resMap.put("goodsData", dataMap); // 商品信息
			resMap.put("totalPrice", totalPrice); // 总价
			resMap.put("buyNum", params.get("buyNum")); // 购买数量
			
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "校验成功!"));
			log.info("【" +tradeId+ "】---【套餐立即购买参数校验】---【返回结果】---" + resMap.toString());
		} catch (Exception e) {
			log.error("【" +tradeId+ "】---【套餐立即购买参数校验】---【异常】---{}", e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
			return resMap;
		}
		log.info("【" +tradeId+ "】---【套餐立即购买参数校验】---【结束】---");
		return resMap;
	}

	@Override
	public Map<String, Object> saveSubmitOrder(Map<String, Object> params, String tradeId) {
		log.info("【" +tradeId+ "】---【订单提交】---【开始】");
		Map<String, Object> resMap = new HashMap<String, Object>();
		PackageOrderInfo pi =new PackageOrderInfo(); //构建订单信息
		boolean lock = false;
		try {
			// 校验参数
			if (params == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数错误!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【订单提交】-----【params】" + params.toString());
			if (params.get("userId") == null || "".equals(params.get("userId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数用户id不能为空!"));
				return resMap;
			}
			//防止重复提交
			if (!isRepeatSubmit(params.get("submitToken"), params.get("userId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "repeatSubmit", "请不要重复提交!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【订单提交】-【清除防重锁】");
			jedisService.del(RedisConstant.USER_PACKAGE_SUBMIT_TOOKEN + params.get("userId"));

			log.info("【" +tradeId+ "】---【订单提交】-【校验参数】");
			//1、校验订单参数
			resMap = checkOrderParams(params, pi, tradeId);
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				resMap.put("result", ri);
				return resMap;
			}
			log.info("【" +tradeId+ "】---【订单提交】-【获取锁】", tradeId);
			lock = jedisService.lock(RedisConstant.PACKAGE_GOODS_LOCK + pi.getGoodsPackageId(), 40000, 15);
			if (!lock) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "get_lock_error", "请重新结算!"));
				return resMap;
			} else {
				log.info("【" +tradeId+ "】---【订单提交】-【保存订单数据】");
				//2、扣减库存
				resMap = updateStock(pi,tradeId);
				ResultInfo stockResult = (ResultInfo) resMap.get("result");
	            if (ResultInfo.ERROR.equals(stockResult.getState())) {
	            	resMap.put("result", (ResultInfo) ResultUtil.initResult(ResultInfo.ERROR, stockResult.getCode(),
	                        "扣减库存异常！", "", "01"));
	                return resMap;
	            }
				//3、生成交易订单 /生成订单主表信息（套餐）/生成订单附表信息（套餐）/取消订单
	            resMap = saveOrderGoods(pi,tradeId);
				return resMap;
			}
		} catch (Exception e) {
			log.error("[" + tradeId + "]---【订单提交】---【异常】-----" + Exceptions.getStackTraceAsString(e));
			resMap.put("result",
					ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		} finally {
			if (lock) {
				jedisService.unlock(RedisConstant.PACKAGE_GOODS_LOCK + pi.getGoodsPackageId());
			}
			ResultInfo ri = (ResultInfo) resMap.get("result");
			if (ResultInfo.ROLLBACK.equals(ri.getIsRollBack())) {
				log.info("[" + tradeId + "]---【订单提交】---【异常事务回滚】---{}---{}", ri.getMessage(), ri.getCode());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
			if (ResultInfo.ERROR.equals(ri.getState())) {
				log.error("【" +tradeId+ "】---【订单提交】-【异常】-【{}：{}】", ri.getCode(), ri.getMessage());
			} else {
				log.info("【" +tradeId+ "】---【订单提交】-【成功】");
			}
			log.info("【" +tradeId+ "】---【订单提交】-【结束】");
		}
	}
	
	/**
	 * 校验订单下单参数
	 * @param params 订单参数
	 * @param tradeId 流水号
	 * @return
	 */
	public Map<String, Object> checkOrderParams(Map<String, Object> params,PackageOrderInfo pi, String tradeId) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		log.info("【" +tradeId+ "】---【校验订单下单参数】-----【开始】");
		try {			
			// 校验参数
			if (params == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数错误!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【校验订单下单参数】-----【params】" + params.toString());
			if (params.get("goodsPackageId") == null || "".equals(params.get("goodsPackageId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数商品套餐id不能为空!"));
				return resMap;
			}
			if (params.get("buyNum") == null || Integer.parseInt("" + params.get("buyNum")) <= 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数购买数量必须大于零!"));
				return resMap;
			}
			if (params.get("userId") == null || "".equals(params.get("userId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数用户id不能为空!"));
				return resMap;
			}
			if (params.get("addressId") == null || "".equals(params.get("addressId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数用户地址id不能为空!"));
				return resMap;
			}
			
			// 验证金额
			if (params.get("totalPrice") == null || new BigDecimal(params.get("totalPrice").toString()).compareTo(BigDecimal.ZERO) <= 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "price_error", "支付金额错误!"));
				return resMap;
			}

			// 验证用户是否实名
			UserReal userReal = accountService.isReal(Long.parseLong(params.get("userId").toString()));
			String userRealUrl = getUserRealUrl(userReal);
			if (StringUtils.isNotEmpty(userRealUrl)) {
				resMap.put("userRealUrl", userRealUrl+ "?returnUrl=" + h5Domain + "/wap/goodspackage/view?id="
						+ params.get("goodsPackageId"));
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_real", "用户未实名认证!"));
				return resMap;
			}
			// 判断商品是否存在
			Map<String, Object> pacResMap = goodsPackageService.selectRecordByKey(Long.parseLong("" + params.get("goodsPackageId")));
			log.info("【" +tradeId+ "】---【校验订单下单参数】-----【判断商品是否存在】" + pacResMap.toString());
			ResultInfo ri = (ResultInfo) pacResMap.get("result");
			if (ResultInfo.ERROR.equals(ri.getState())) {
				resMap.put("result", ri);
				return resMap;
			}
			@SuppressWarnings("unchecked")
			Map<String, Object> dataMap = (Map<String, Object>) pacResMap.get("data");
			if (dataMap == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "获取商品套餐异常!"));
				return resMap;
			}
			if (dataMap.get("state") == null || !GoodsContant.State.UP.getValue().equals(dataMap.get("state"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品非上架状态!"));
				return resMap;
			}
			if (GoodsContant.SaleType.YES.getValue().equals(dataMap.get("saleType"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品已售罄!"));
				return resMap;
			}
			//实际售出数量
			int realSaleNum = 0;
			if (dataMap.get("realSaleNum") != null) {
				realSaleNum=Integer.parseInt("" + dataMap.get("realSaleNum"));
			}
			//库存
			int stockNum = 0;
			if (dataMap.get("stockNum") != null) {
				stockNum=Integer.parseInt("" + dataMap.get("stockNum"));
			}
			if (stockNum <= realSaleNum ) { // 没库存则直接返回
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "商品已售罄!"));
				return resMap;
			}
			Integer minShopNum = 0; //最小起售数量
			if (dataMap.get("minShopNum") != null) {
				minShopNum=Integer.parseInt("" + dataMap.get("minShopNum"));
			}
			Integer maxShopNum = 0; //最大起售数量
			if (dataMap.get("maxShopNum") != null) {
				maxShopNum=Integer.parseInt("" + dataMap.get("maxShopNum"));
			}
			if (Integer.parseInt("" + params.get("buyNum")) > maxShopNum || Integer.parseInt("" + params.get("buyNum")) < minShopNum) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "购买数量有误!"));
				return resMap;
			}
			// 判断金额
			BigDecimal totalPrice = DataUtil.mul(2, dataMap.get("price"), params.get("buyNum"));

			if (totalPrice.compareTo(new BigDecimal(params.get("totalPrice").toString())) != 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "支付金额错误!"));
				return resMap;
			}
			// 验证收货地址
			Address address = userService.getAddressById(Integer.parseInt(params.get("addressId").toString()));
			if (address == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "address_empty", "收货地址不能为空!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【校验订单下单参数】-----【收货地址成功】" + address.toString() );
			List<OrderConfig> oc = orderMapper.getOrderConfig();
			if (oc == null || oc.size() == 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
				return resMap;
			}
			//校验用户未支付订单数量
			Map<String, Object> payParams = new HashMap<String, Object>();
			payParams.put("userId", params.get("userId"));
			payParams.put("state", OrderConstant.State.notpay.getValue());
			int orderCnt = orderMapper.getOrderCntByUserId(payParams);
			if (oc.get(0).getOrderNotpayMaxNum() <= orderCnt) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "请不要重复购买!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【校验订单下单参数】-----【未支付订单数量】" + oc.get(0).getOrderNotpayMaxNum());
			//获取套餐详情 
			Map<String, Object> detailParams = new  HashMap<String, Object>();
			detailParams.put("goodsPackageId", params.get("goodsPackageId"));
			Map<String, Object> detailMap = goodsPackageDetailService.selectByPackageId(detailParams);
			log.info("【" +tradeId+ "】---【校验订单下单参数】-----【获取套餐详细信息 】" + detailMap.toString());
			ResultInfo re = (ResultInfo) detailMap.get("result");
			if (ResultInfo.ERROR.equals(re.getState())) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "getPackagedetail_error", "获取套餐详细信息异常!"));
				return resMap;
			}
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> detMap = (List<Map<String, Object>>) detailMap.get("data");
			if (detMap == null || detMap.size() <= 0) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", "获取商品套餐详情无数据!"));
				return resMap;
			}
			pi.setAddress(address);
			pi.setTotalPrice(totalPrice);
			pi.setPayPrice(new BigDecimal(params.get("totalPrice").toString()));
			pi.setAddressId(Integer.parseInt(params.get("addressId").toString()));
			pi.setUserId(Integer.parseInt(params.get("userId").toString()));
			pi.setGoodsPackageId(Long.parseLong("" + params.get("goodsPackageId")));
			pi.setBuyNum(Integer.parseInt(params.get("buyNum").toString()));
			pi.setPackageGood(dataMap);
			pi.setPackageGoodDetails(detMap);
			
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "校验成功!"));
			log.info("【" +tradeId+ "】---【校验订单下单参数】-----【结束】");
		} catch (Exception e) {
			log.error("【" +tradeId+ "】---【校验订单下单参数】-----【异常】"+ Exceptions.getStackTraceAsString(e));
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
		}
		return resMap;
	}
	
	/**
	 * 扣减库存
	 * @param pi 提交订单参数
	 * @param tradeId 交易流水
	 * @return Map<String, Object>
	 */
    public Map<String, Object> updateStock(PackageOrderInfo pi, String tradeId) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            log.info("【" +tradeId+ "】---【扣减库存】---【开始】");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", pi.getGoodsPackageId());
            params.put("num", pi.getBuyNum());
            int rec=payMapper.updatePackageGoodsStockNum(params);
            if (rec <= 0) {
                log.error("【" +tradeId+ "】---【扣减库存】---【库存不足】-----");
                result.put("result",ResultUtil.initResult(ResultInfo.ERROR, "stock_less", "库存不足！", "", "01"));
                return result;
            }
            result.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "扣减库存!"));
            log.info("【" +tradeId+ "】---【扣减库存】---【结束】-----");
        } catch (Exception e) {
            log.error("【" +tradeId+ "】---【扣减库存】---【异常！】-----" + Exceptions.getStackTraceAsString(e));
            result.put("result",ResultUtil.initResult(ResultInfo.ERROR, "stock_exception", "扣减异常！", "", "01"));
        }
        return result;
    }
	/**
	 * 保存订单
	 * 
	 * @param pi
	 *            pi
	 * @return 保存结果
	 */
	public Map<String, Object> saveOrderGoods(PackageOrderInfo pi, String tradeId) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        log.info("【" +tradeId+ "】---【保存订单】---【开始】-----");
		try {
			String curTime = DateUtil.getTime();
			TransactionFlow tf = new TransactionFlow();
			tf.setUserId(pi.getUserId());
			tf.setTotalPrice(pi.getTotalPrice());
			tf.setPayPrice(pi.getPayPrice());
			tf.setPriceState(BillConstant.MoneyState.out.getValue());
			tf.setRemark(pi.getPackageGood().get("name") + "(" + pi.getBuyNum()+ "份)");
			tf.setState(PayConstant.State.notpay.getValue());
			tf.setType(BillConstant.Type.consume.getValue());
			tf.setCreateTime(curTime);
			payMapper.saveTransactionFlow(tf); //生成交易订单
			tf.setCode(CustomUtil.orderCode(3, tf.getId(), pi.getUserId()));
			int num = payMapper.updateTransactionFlowCode(tf);
			if (num != 1) {
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【保存订单】---【交易订单处理成功】-----");
			// 插入订单
			Order order = new Order();
			order.setTransactionId(tf.getId());
			order.setUserId(pi.getUserId());
			order.setType(OrderConstant.Type.packageGoods.getValue());
			order.setState(OrderConstant.State.notpay.getValue());
			order.setTotalPrice(pi.getTotalPrice());
			order.setRealPrice(pi.getPayPrice());
			order.setCreateTime(curTime);
			order.setUpdateTime(curTime);
			payMapper.saveOrder(order); //生成主订单
			order.setCode(CustomUtil.orderCode(3, order.getId(), pi.getUserId()));
			int snum = payMapper.updateOrderCode(order);
			if (snum != 1) {
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【保存订单】---【订单处理成功】-----");			
			OrderPackage record =new OrderPackage();
			record.setBuyNum(pi.getBuyNum());
			record.setContent(pi.getPackageGood().get("content").toString());
			record.setCreateTime(curTime);
			record.setEndUseTime(pi.getPackageGood().get("endUseTime").toString());
			record.setEquityCycle(pi.getPackageGood().get("equityCycle").toString());
			record.setGoodsPackageId(pi.getGoodsPackageId());
			record.setName(pi.getPackageGood().get("name").toString());
			record.setOrderId(order.getId());
			record.setPackageEfficacy(pi.getPackageGood().get("packageEfficacy").toString());
			record.setPicture(pi.getPackageGood().get("picture").toString());
			record.setPrice(new BigDecimal(pi.getPackageGood().get("price").toString()));
			record.setTimeId(Integer.parseInt(pi.getPackageGood().get("timeId").toString()));
			record.setTopPicture(pi.getPackageGood().get("topPicture").toString());
			record.setUserId(pi.getUserId());
			record.setThumbnail(pi.getPackageGood().get("thumbnail").toString());
			
			int oNum = orderPackageMapper.insert(record); //生成订单套餐主附表
			if (oNum != 1) {
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【保存订单】---【订单套餐附表处理成功】-----");
			
			List<Map<String, Object>> detListMap = (List<Map<String, Object>>) pi.getPackageGoodDetails();
			Address address = pi.getAddress();
			List<OrderPackageDetail> detailList= new ArrayList<OrderPackageDetail>();
			//订单套餐详情 
			for (Map<String, Object> dMap:detListMap) {
				OrderPackageDetail rec = new OrderPackageDetail();
				rec.setBaseId(Integer.parseInt(""+dMap.get("baseId")));
				rec.setBaseName((String)dMap.get("baseName"));
				rec.setEndTime((String)dMap.get("endTime"));
				rec.setStartTime((String)dMap.get("startTime"));
				rec.setGoodsId(Integer.parseInt(""+dMap.get("goodsId")));
				rec.setGoodsName((String)dMap.get("goodsName"));
				rec.setGoodsPackageId(Long.parseLong(""+dMap.get("goodsPackageId")));
				rec.setGoodsPdetailId(Long.parseLong(""+dMap.get("id")));
				rec.setGoodsSpecId(Integer.parseInt(""+dMap.get("goodsSpecId")));
				rec.setMeasureUnit((String)dMap.get("measureUnit"));
				rec.setMeasureWeigh(new BigDecimal(""+dMap.get("measureWeigh")));
				rec.setThumb((String)dMap.get("thumb"));
				rec.setUserId(pi.getUserId());
				rec.setOrderId(order.getId());
				rec.setBuyNum(pi.getBuyNum());
				rec.setCreateTime(curTime);
				rec.setReceiverAddress(address.getAddress());
				rec.setReceiverCityId(address.getCityId());
				rec.setReceiverCountryId(address.getCountryId());
				rec.setReceiverTownId(address.getTownId());
				rec.setReceiverName(address.getName());
				rec.setReceiverPhone(address.getPhone());
				rec.setReceiverProvinceId(address.getProvinceId());
				
				detailList.add(rec);
			}
			if (detailList.size() <= 0) {
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【保存订单】-----【订单套餐详情  】---【params】-----{}",detailList.toString());
			int odNum = orderPackageDetailMapper.insertRecords(detailList);	// 插入订单套餐商品详情		
			log.info("【" +tradeId+ "】---【保存订单】-----【订单套餐详情  】-----");
			if (odNum <= 0) {
				resMap.put("result",
						ResultUtil.initResult(ResultInfo.ERROR, "confirm_again", "请重新结算!", null, ResultInfo.ROLLBACK));
				return resMap;
			}
			// 加入订单取消队列
			orderService.saveAutoCancelOrder(order.getId());

			resMap.put("transactionCode", tf.getCode());
			resMap.put("lightpayUrl", domain+"/wap/lightpay/lightPayCashier?transactionCode=" + tf.getCode());
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "保存成功!"));
		} catch (Exception e) {
			log.error("【" +tradeId+ "】---【保存订单】---【异常！】-----" + Exceptions.getStackTraceAsString(e));
			resMap.put("result",ResultUtil.initResult(ResultInfo.ERROR, "saveorder_exception", "保存订单异常！", "", "01"));
		}
		log.info("【" +tradeId+ "】---【保存订单】---【结束】-----");
		return resMap;
	}
	
	/**
	 * 验证token
	 * @param token 令牌
	 * @param userId 用户标识
	 * @return true or false
	 */
	private boolean isRepeatSubmit(Object token, Object userId) {
		log.info("【提交TOKEN】:{}", token.toString());
		if (StringUtils.isEmpty(token.toString())) {
			return false;
		}
		String serverToken = jedisService.get(RedisConstant.USER_PACKAGE_SUBMIT_TOOKEN + userId.toString());
		log.info("【缓存TOKEN】:{}", serverToken);
		if (StringUtils.isEmpty(serverToken)) {
			return false;
		}
		if (!token.toString().equals(serverToken)) {
			return false;
		}
		return true;
	}
	/**
	 * 实名认证跳转地址
	 * 
	 * @param userReal
	 *            实名认证信息
	 * @return 返回实名认证跳转地址
	 */
	public String getUserRealUrl(UserReal userReal) {
		if (userReal == null) {
			return "redirect:" + h5Domain + "/legalize";
		} else {
			switch (userReal.getState()) {
			case "01":
				return "redirect:" + h5Domain + "/legalizeHome";
			case "03":
				if (userReal.getCommitCount() < AccountManager.MAXCERT) {
					return "redirect:" + h5Domain + "/legalize";
				} else {
					return "redirect:" + h5Domain + "/verified";
				}
			default:
				return null;
			}
		}

	}

	@Override
	public Map<String, Object> getOrderRightRecords(Map<String, Object> params) {
		log.info("【订单套餐权益列表服务】---【开始】---");
		Map<String, Object> result = new HashMap<String, Object>();
		if (params == null) {
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "传入参数不能为null!"));
			return result;
		}
		log.info("【订单套餐权益列表服务】---【params】---{}", params.toString());
		if (params.get("goodsPackageId") == null || "".equals(params.get("goodsPackageId"))) { // 套餐id
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "传入套餐id不能为空!"));
			return result;
		}
		if (params.get("orderId") == null || "".equals(params.get("orderId"))) { // 订单套餐id
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "传入订单id不能为空!"));
			return result;
		}
		
		try {
			// 查询产品套餐信息
			Map<String, Object> pglist = orderPackageMapper.selectOrderPackageByOrder(params);
			log.info("【订单套餐权益列表服务】---【订单套餐新获取成功】---");
			List<Map<String, Object>> list = orderPackageDetailMapper.getRecordsByTime(params);
			log.info("【订单套餐权益列表服务】---【批次时间获取成功】---");
			// 时间批次
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> pam = new HashMap<String, Object>();
				pam.put("goodsPackageId", params.get("goodsPackageId"));
				pam.put("userId", params.get("userId"));
				pam.put("orderId", params.get("orderId"));
				pam.put("startTime", list.get(i).get("startTime"));
				pam.put("endTime",list.get(i).get("endTime"));
				List<Map<String, Object>> detailList = orderPackageDetailMapper.getOrderPackagedetails(pam);
				if (detailList == null || detailList.size() <= 0) {
					log.error("【订单套餐权益列表服务】---【detailList异常】---{}", list.get(i).toString());
					result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "获取发货时间范围内商品异常"));
					return result;
				}
				// 放入每批次的商品列表
				list.get(i).put("detailList", detailList);
			}
			log.info("【订单套餐权益列表服务】---【批次时间内商品列表获取成功】---");
			result.put("packagedata", pglist);
			result.put("data", list);
			result.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "ok", ""));
		} catch (Exception e) {
			log.error("【订单套餐权益列表服务】---【异常】---{}", e);
			result.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常"));
		}
		log.info("【订单套餐权益列表服务】---【结束】---");
		return result;
	}
	/**
	 * 实名认证状态
	 */
	@Override
	public Map<String, Object> isRealName(Map<String, Object> params, String tradeId) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			// 校验参数
			if (params == null) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数错误!"));
				return resMap;
			}
			log.info("【" +tradeId+ "】---【实名认证参数校验】-----【params】" + params.toString());
			if (params.get("goodsPackageId") == null || "".equals(params.get("goodsPackageId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数商品套餐id不能为空!"));
				return resMap;
			}
			if (params.get("userId") == null || "".equals(params.get("userId"))) {
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "param_error", "参数用户id不能为空!"));
				return resMap;
			}
			// 验证用户是否实名
			UserReal userReal = accountService.isReal(Long.parseLong("" + params.get("userId")));
			log.info("【" +tradeId+ "】---【实名认证】");
			String userRealUrl = getUserRealUrl(userReal);
			if (StringUtils.isNotEmpty(userRealUrl)) {
				resMap.put("userRealUrl", userRealUrl+ "?returnUrl=" + h5Domain + "/mealDetails?id="
						+ params.get("goodsPackageId"));
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "user_not_real", "用户未实名认证!"));
				return resMap;
			}
			resMap.put("userReal", userReal); // 实名认证
			resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "校验成功!"));
			log.info("【" +tradeId+ "】---【实名认证】---【返回结果】---" + resMap.toString());
		} catch (Exception e) {
			log.error("【" +tradeId+ "】---【实名认证】---【异常】---{}", e);
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!"));
			return resMap;
		}
		log.info("【" +tradeId+ "】---【实名认证】---【结束】---");
		return resMap;
	}
}
